package cn.piesat.controller;

import cn.piesat.dto.MailmsgConfigDTO;
import cn.piesat.dto.PiesatUserInfoDTO;
import cn.piesat.service.intf.MailmsgConfigService;
import cn.piesat.service.intf.UserInfoService;
import cn.piesat.util.JedisUtils;
import cn.piesat.util.RandomValidateCodeUtil;
import cn.piesat.util.ResponseWrapperUtil;
import cn.piesat.util.config.FieldStaticConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 各种验证码发送
 * @author 奚好雷
 *
 */
@RestController
@RequestMapping("/send")
public class SendController {

	private static final Logger logger = LoggerFactory.getLogger(SendController.class);

	@Autowired
	private UserInfoService userInfoService;
	
	@Autowired
	private MailmsgConfigService mailmsgConfigService;
	
	/**
	 * 发送邮箱验证码
	 * @param email
	 * @param type 类型（login 登录 register 注册 updatePassword 修改密码）
	 * @return
	 */
	@GetMapping("/mail/code/{email}/{type}")
	public String sendEmail(@PathVariable("email")String email,
							@PathVariable("type")String type) {
		String template = "验证码为${code}";
		List<MailmsgConfigDTO> list = mailmsgConfigService.getTypeAndStateMessage("mail", 0);
		if(list.isEmpty()) {
			return ResponseWrapperUtil.executeCustomTips("false", "邮件功能被禁用");
		}
		PiesatUserInfoDTO dto = userInfoService.findByEmail(email);
		Jedis jedis = JedisUtils.getJedis();
		try {
			Map<String, String> map = jedis.hgetAll(FieldStaticConfig.MAILCONFIG_REDIS_KEY);
			if("login".equals(type)) {
				if(dto == null) {
					return ResponseWrapperUtil.executeCustomTips("false", "该邮箱用户不存在");
				}
				if (StringUtils.isNotBlank(map.get("login"))){
					template = map.get("login");
				}
			} else if ("register".equals(type)) {
				if(dto != null) {
					return ResponseWrapperUtil.executeCustomTips("false", "该邮箱用户已存在");
				}
				if (StringUtils.isNotBlank(map.get("register"))){
					template = map.get("register");
				}
			} else if ("updatePassword".equals(type)) {
				if(dto == null) {
					return ResponseWrapperUtil.executeCustomTips("false", "该邮箱用户不存在");
				}
				if (StringUtils.isNotBlank(map.get("updatePassword"))){
					template = map.get("updatePassword");
				}			}
			String code =(int)((Math.random()*9+1)*100000)+"";
			JavaMailSenderImpl sender = new JavaMailSenderImpl();
			sender.setHost(map.get("spring.mail.host"));
			sender.setUsername(map.get("spring.mail.username"));
			sender.setPassword(map.get("spring.mail.password"));
			sender.setDefaultEncoding(map.get("spring.mail.default-encoding"));
			SimpleMailMessage message = new SimpleMailMessage();
			message.setCc("xhl_0519@163.com");
	        message.setTo(email);//收信人
	        message.setSubject(map.get("subject"));//主题
	        message.setText(template.replace("${code}", code));//内容
	        message.setFrom(map.get("spring.mail.username"));//发信人
	        sender.send(message);
	        String key = FieldStaticConfig.EMAIL_VERIFYCODE_REDIS_PREFIX + email;
	        if(!jedis.exists(key)) {
	        	jedis.set(key , code,"NX","EX",FieldStaticConfig.VERIFYCODE_TIME_REDIS);
	        } else {
	            jedis.set(key,code);
	            jedis.expire(key, FieldStaticConfig.VERIFYCODE_TIME_REDIS);
	        }
		}catch (Exception e) {
			return ResponseWrapperUtil.executeCustomTips("false", "发送邮件失败");
		} finally {
			JedisUtils.close(jedis);
		}
		return ResponseWrapperUtil.executeCustomTips("true", "发送邮件成功");
	}
	
	/**
	 * 获取图片验证码
	 * @param request
	 * @param response
	 */
	@GetMapping("/img/code")
	public void getImgVerifyCode(HttpServletRequest request, HttpServletResponse response) {
		try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
			logger.error("图片验证码异常：{}",e.getLocalizedMessage(),e);
        }
	}
	
	/**
     * 发送手机验证码 保存到Redis中
     * @param mobile 手机号码
     * @param type 类型（login 登录 register 注册 updatePassword 修改密码）
     * @return
     */
    @GetMapping("/sms/code/{sms}/{type}")
    public String getMobileCode(@PathVariable("sms")String mobile,
    							@PathVariable("type")String type){
		PiesatUserInfoDTO dto = userInfoService.findByMobile(mobile);
		String templateCode = null;
        List<MailmsgConfigDTO> list = mailmsgConfigService.getTypeAndStateMessage("sms", 0);
        if(list.isEmpty()) {
        	return ResponseWrapperUtil.executeCustomTips("false","短信验证码功能被禁用");
        }
        Jedis jedis = JedisUtils.getJedis();
        Map<String, String> smsMap = jedis.hgetAll(FieldStaticConfig.SMSCONFIG_REDIS_KEY);
        Map<String,String> map = null;
        try {
        	if("login".equals(type)) {
            	if(dto == null) {
            		return ResponseWrapperUtil.executeCustomTips("false","该用户不存在");
            	}
            	templateCode = smsMap.get("sms_login");
            } else if ("register".equals(type)) {
            	if(dto != null) {
            		return ResponseWrapperUtil.executeCustomTips("false","您要注册的用户已经存在");
            	}
            	templateCode = smsMap.get("sms_register");
            } else if ("updatePassword".equals(type)) {
            	if(dto == null) {
            		return ResponseWrapperUtil.executeCustomTips("false","该用户不存在");
            	}
            	templateCode = smsMap.get("sms_updatePassword");
            }
            if(templateCode == null) {
            	return ResponseWrapperUtil.executeCustomTips("false","没有合适的模板");
            }
            String code =(int)((Math.random()*9+1)*100000)+"";
            String accessKeyId = smsMap.get("accessKeyId");
            String accessSecret = smsMap.get("accessSecret");
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
            IAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.setMethod(MethodType.POST);
            request.setDomain(smsMap.get("domain"));
            request.setVersion("2017-05-25");
            request.setAction("SendSms");
            request.putQueryParameter("RegionId", "cn-hangzhou");
            request.putQueryParameter("PhoneNumbers", mobile);
            request.putQueryParameter("SignName", smsMap.get("signName"));
            request.putQueryParameter("TemplateCode", templateCode);
            request.putQueryParameter("TemplateParam", "{\"code\":"+code+"}");
            CommonResponse response = client.getCommonResponse(request);
            map = JSON.parseObject(response.getData(),new TypeReference<Map<String,String>>(){});
            if("OK".equals(map.get("Code"))) {
                String key = FieldStaticConfig.MOBILE_VERIFYCODE_REDIS_PREFIX + mobile;
                if(!jedis.exists(key)) {
                	jedis.set(key , code,"NX","EX",FieldStaticConfig.VERIFYCODE_TIME_REDIS);
                } else {
                    jedis.set(key,code);
                    jedis.expire(key, FieldStaticConfig.VERIFYCODE_TIME_REDIS);
                }
                return ResponseWrapperUtil.executeCustomTips("true","发送成功!");
            }
		}catch (ServerException e) {
			logger.error("发送阿里云短信服务器异常:{}",e.getLocalizedMessage(),e);
		}catch (ClientException e) {
			logger.error("发送阿里云短信客户端异常:{}",e.getLocalizedMessage(),e);
		} finally {
			JedisUtils.close(jedis);
		}
        return ResponseWrapperUtil.executeCustomTips("false",map.get("Message"));
    }

    
    /**
     * 	手机验证码的校验
     * @param code
     * @return
     */
    @GetMapping("/verify/{code}/{formType}/{value}")
    public String verifyMobile(@PathVariable("code")String code,
    						   @PathVariable("formType")String formType,
    						   @PathVariable("value")String value) {
    	String key;
    	if("telephone".equals(formType)) {
    		if(StringUtils.isBlank(value)) {
    			return ResponseWrapperUtil.executeCustomTips("false", "请输入手机号码");
    		}
    		key = FieldStaticConfig.MOBILE_VERIFYCODE_REDIS_PREFIX;
    	} else if ("email".equals(formType)) {
    		if(StringUtils.isBlank(value)) {
    			return ResponseWrapperUtil.executeCustomTips("false", "请输入邮箱");
    		}
    		key = FieldStaticConfig.EMAIL_VERIFYCODE_REDIS_PREFIX;
    	} else {
    		return ResponseWrapperUtil.executeCustomTips("false", "字段不满足条件");
    	}
    	if(StringUtils.isBlank(code)) {
    		return ResponseWrapperUtil.executeCustomTips("false", "请输入验证码");
    	}
    	
    	Jedis jedis = JedisUtils.getJedis();
    	String reCode = jedis.get(key + value);
    	try {
    		if(StringUtils.isBlank(reCode)) {
        		return ResponseWrapperUtil.executeCustomTips("false", "验证码过期");
        	}
        	if(!code.equalsIgnoreCase(reCode)) {
        		return ResponseWrapperUtil.executeCustomTips("false", "验证码错误");
        	}
        	jedis.del(key + value);
    	}finally {
			JedisUtils.close(jedis);
		}
    	return ResponseWrapperUtil.executeCustomTips("true", "验证码正确");
    }

	/**
	 * 多人发送邮件
	 * @param json
	 * {
	 *     “to":"",收件人邮箱用户","隔开,
	 *     "content":""邮件内容,
	 *     "subject":""邮件主题
	 * }
	 * @return
	 */
	@PostMapping("/warn/mail")
	public String sendWarnMail(@RequestBody String json){
		Map params = JSON.parseObject(json, Map.class);
		if(StringUtils.isBlank(params.get("to").toString())){
			return ResponseWrapperUtil.executeCustomTips("false","请输入邮箱！");
		}
		String to = params.get("to").toString();
		String [] strs = null;
		if (to.contains(",")){
			strs = to.split(",");
		} else {
			strs = new String []{to};
		}
		String subject = params.get("subject").toString();
		if (StringUtils.isBlank(subject)) {
			return ResponseWrapperUtil.executeCustomTips("false","请输入主题！");
		}
		String content = params.get("content").toString();

		Jedis jedis = JedisUtils.getJedis();
    	try{
			Map<String, String> map = jedis.hgetAll(FieldStaticConfig.MAILCONFIG_REDIS_KEY);
			JavaMailSenderImpl sender = new JavaMailSenderImpl();
			sender.setHost(map.get("spring.mail.host"));
			sender.setUsername(map.get("spring.mail.username"));
			sender.setPassword(map.get("spring.mail.password"));
			sender.setDefaultEncoding(map.get("spring.mail.default-encoding"));
			SimpleMailMessage message = new SimpleMailMessage();
			message.setCc("xhl_0519@163.com");//经常被当作垃圾邮件所以抄送自己一份
			message.setTo(strs);//收信人
			message.setSubject(subject);//主题
			message.setText(content);//内容
			message.setFrom(map.get("spring.mail.username"));//发信人
			sender.send(message);
		}catch (Exception e) {
			return ResponseWrapperUtil.executeCustomTips("false", "发送邮件失败");
		} finally {
			JedisUtils.close(jedis);
		}
    	return ResponseWrapperUtil.executeCustomTips("true", "发送邮件成功");
    }

}
